package ca.llsutherland.squash.facade;

import java.util.List;

import ca.llsutherland.squash.configuration.SquashLadderConfiguration;
import ca.llsutherland.squash.dao.CourtStylesDao;
import ca.llsutherland.squash.dao.RolesDao;
import ca.llsutherland.squash.domain.Clock;
import ca.llsutherland.squash.domain.CourtStyle;
import ca.llsutherland.squash.domain.Role;
import ca.llsutherland.squash.domain.helper.CourtStylesHelper;
import ca.llsutherland.squash.domain.helper.RolesHelper;
import ca.llsutherland.squash.exceptions.ValidationException;
import ca.llsutherland.squash.persistence.Transaction;
import ca.llsutherland.squash.persistence.TransactionHandler;

public class AutoloadFacade {

    protected TransactionHandler transactionHandler = TransactionHandler.getInstance();
    

    public void autoloadCourtStyles() {
        
        Transaction t = new Transaction() {
            public Object executeTransaction() throws ValidationException {
                
                List<String> courtStyles = SquashLadderConfiguration.getInstance().getAllSortedCourtStyles();
                Long i = 1L;
                for (String name : courtStyles) {
                    CourtStyle courtStyle = CourtStylesDao.getInstance().findByName(name);
                    if(courtStyle == null) {
                        CourtStyle newCourtStyle = CourtStylesHelper.createNewCourtStyle(name, new Clock(System.currentTimeMillis()), new Clock(System.currentTimeMillis()), i);
                        CourtStylesDao.getInstance().create(newCourtStyle);
                    }
                    i++;
                }
                return null;
            }
        };
        this.transactionHandler.runTransaction(t);
    }


    public void autoloadRoles() {
        Transaction t = new Transaction() {
            public Object executeTransaction() throws ValidationException {
                List<String> roleNames = SquashLadderConfiguration.getInstance().getAllSortedRoles();
                Long i = 1L;
                for (String name : roleNames) {
                    Role role = RolesDao.getInstance().findByName(name);
                    if(role == null) {
                        Role newRole = RolesHelper.createNewRole(name, new Clock(System.currentTimeMillis()), new Clock(System.currentTimeMillis()), i);
                        RolesDao.getInstance().create(newRole);
                    }
                    i++;
                }
                
                return null;
            }
        };
        this.transactionHandler.runTransaction(t);
        
    }
}
